<template>
    <div class="tag_list_container" :class="{ flex: showTagList }">
        <template v-if="showTagList">
            <el-tag v-for="(item, index) in tagList" :key="index" v-bind="item"
                    v-on="listenerEvent">{{ item.text }}</el-tag>
        </template>
        <template v-else>{{ cellValue || '' }}</template>
    </div>
</template>

<script>
import customAttributes, { ElTag, genProps } from "../../custom/attributes";

export default {
    name: "TagList",
    props: {
        params: Object,
        showTag: {
            type: Boolean,
            default: false,
        },
        tagField: {
            type: String,
            default: 'text',
        },
        tagTextFun: {
            type: Function,
            default: null,
        },
        events: {
            type: Object,
            default: null,
        },
        disableTransitions: {
            type: Boolean,
            default: true,
        },
    },
    data() {
        return {};
    },
    computed: {
        cellValue() {
            let { row, column } = this.params;
            return this.$XEUtils.get(row, column.property);
        },
        tagList() {
            let check = !this.$XEUtils.isEmpty(this.cellValue);
            if (check && this.cellValue.startsWith('[')) {
                let list = JSON.parse(this.cellValue);
                return list.map(item => {
                    let props = genProps(ElTag, item);
                    props.text = item[this.tagField];
                    if (typeof this.tagTextFun === 'function') {
                        props.text = this.tagTextFun(item);
                    }
                    delete props.listenerEvent;
                    props.disableTransitions = this.disableTransitions;
                    return props;
                });
            }
            return [];
        },
        listenerEvent() {
            let listener = {};
            let { row, column } = this.params;
            let defaultProps = $.extend({}, ElTag);
            if (defaultProps.listenerEvent && this.events) {
                for (let ev in defaultProps.listenerEvent) {
                    listener[ev] = event => {
                        typeof this.event[ev] === 'function' && this.event[ev].call(this, event, row, column);
                    };
                }
            }
            return listener;
        },
        showTagList() {
            return this.showTag && this.$utils.isNotEmptyList(this.tagList);
        },
    },
    methods: {
    },
}
</script>

<style scoped lang="less">
.tag_list_container {
    display: contents;

    &.flex {
        display: flex;
        align-items: center;
        gap: 5px;
        flex-wrap: wrap;
    }
}
</style>